import { GetAll } from '@/api/Chat'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import Vue from 'vue'
import { Notification } from 'element-ui'

const state = {
  users: [],
  sessions: {},
  currentSession: null,
  filterKey: '',
  stomp: null,
  isDot: {}
}

const mutations = {
  changeCurrentSession(state, currentSession) {
    state.currentSession = currentSession
    var username = JSON.parse(window.sessionStorage.getItem('user')).username
    Vue.set(state.isDot, username + '#' + currentSession.username, false)
  },
  addMessage(state, msg) {
    var username = JSON.parse(window.sessionStorage.getItem('user')).username
    if (!state.sessions[username + '#' + msg.to]) {
      // state.sessions[username + '#' + msg.to] = []
      Vue.set(state.sessions, username + '#' + msg.to, [])
    }
    state.sessions[username + '#' + msg.to].push({
      content: msg.content,
      date: new Date(),
      self: !msg.notSelf
    })
  },
  INIT_DATA(state) {
    // 浏览器本地的历史记录可以在这里完成
    const data = localStorage.getItem('vue-chat-session')
    if (data) {
      state.sessions = JSON.parse(data)
    }
  },
  INIT_USERS(state, data) {
    state.users = data
  }
}

const actions = {
  connect(context) {
    context.state.stomp = Stomp.over(new SockJS('/ws/ep'))
    context.state.stomp.connect({}, success => {
      context.state.stomp.subscribe('/user/queue/chat', msg => {
        var receiveMsg = JSON.parse(msg.body)
        if (!context.state.currentSession || receiveMsg.from !== context.state.currentSession.username) {
          Notification.info({
            title: '【' + receiveMsg.fromNickname + '】发来一条消息',
            message: receiveMsg.content.length > 10 ? receiveMsg.content.substring(0, 10) : receiveMsg.content,
            position: 'bottom-right'
          })
          var username = JSON.parse(window.sessionStorage.getItem('user')).username
          Vue.set(context.state.isDot, username + '#' + receiveMsg.from, true)
        }
        receiveMsg.notSelf = true
        receiveMsg.to = receiveMsg.from
        context.commit('addMessage', receiveMsg)
      })
    }, error => {
      console.log('error --> ', error)
    })
  },
  initData(context) {
    context.commit('INIT_DATA')
    GetAll().then((res) => {
      if (res) {
        context.commit('INIT_USERS', res)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
